<?php
class cart{
	private	$itemCount=0;
	private	$items;
	public function __construct()
	{
		$this->iniCart();
	}
	
	function iniCart()
	{
		if (isset($_SESSION["items"]))
			{	
				$this->items =	$_SESSION["items"];
				$this->itemCount = array_sum($this->items);
			}
		else
		{	$_SESSION["items"] = array();
			$this->items= array();
			$this->itemCount=0;	
		}
	}
	
	function delCart()
	{   
		unsert($_SESSION["items"]);
		$this->iniCart();	
	}
	
	function addItem($item, $quantity=1)
	{	if ($item==null) return;
		$objDb = new db();
		$objDb->query("select * from sanpham where masp='$item' ");
		if ($objDb->getRowCount()==0) return;
		
		if 	(isset($_SESSION["items"][$item]))
			$_SESSION["items"][$item] += $quantity;
		else $_SESSION["items"][$item]= $quantity;
		$this->iniCart();
	}
	
	function delItem($item)
	{
		unset($_SESSION["items"][$item]);
		$this->iniCart();
	}
	
	function updateItem($item, $quantity)
	{ 	
		if ($item==null) return;
		if ($quantity<=0) 
			{
			  $this->delItem($item);
			  return;
			}
		if 	(isset($_SESSION["items"][$item]))
			$_SESSION["items"][$item] = $quantity;
		$this->iniCart();
	}
	
	function showGeneral()
	{
		echo "Có:". $this->itemCount." item trong giỏ hàng";
	}
	
	function showDetail()
	{
		//print_r($this->items);	
		if ($this->itemCount==0) 
		{
			echo "Giỏ hàng rỗng"; return;	
		}
		$objDb = new db();
		echo "<table border=1><tr><td>Mã sản phẩm</td><td>Tên sản phẩm</td>";
		echo "<td>Giá</td><td>Số lượng</td><td>Thành tiền</td>";
		echo "<td colspan=\"2\">Thao tác</tr>";
		$sum =0;
		foreach($this->items as $item=>$quanlity)
		{
			$rows = $objDb->select("sanpham", array("masp", "tensp", "dongia"), " masp='$item'");
			if (count($rows)>0)
			{
				$row = $rows[0]; $sum +=($row["dongia"]*$quanlity);
			//print_r($row);
			echo "<tr><td>". $row["masp"]."</td><td>".$row["tensp"]."</td>";
			echo "<td>".$row["dongia"]."</td>";
			echo "<td><input type=text id='cart_{$item}' value='". $quanlity. "'></td>";
			echo "<td align=right>" . number_format($row["dongia"]*$quanlity, 0, "."," "). " VND</td>";
			
			echo "<td><a href=# onclick=\"cartUpdate('cart_{$item}');\">Update</a></td>";
			echo "<td ><a href='index.php?mod=cart&ac=del&idpro=$item'>Xóa</a></td></tr>";
			}
				
		}
		echo "<tr><td colspan=4 align=right>Tổng tiền</td>";
		echo "<td colspan=3>". number_format($sum, 0, ".", " ")." VDN</td></tr>";
		echo "</table>";
	}
	
	}

?>